package com.joysuch.wwyt.common.controller;

import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.common.enums.TemplateTypes;
import com.joysuch.wwyt.dynamicdata.entity.BaseDynamicFieldConfig;
import com.joysuch.wwyt.dynamicdata.service.BaseDynamicFieldConfigService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author ZhangDong
 * @Date 2020/4/27 15:07
 */
@Controller
@RequestMapping("data/template")
@Api(tags = "/bp/exceldataimport模板导入")
@Slf4j
public class TemplateController {

    private static final Logger logger = LoggerFactory.getLogger(TemplateController.class);

    @Autowired
    private BaseDynamicFieldConfigService fieldConfigService;

    @GetMapping("download/{index}")
    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer index) {
        String fileName = TemplateTypes.getFileName(index);
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("index输入不正确");
        }
        String agent = request.getHeader("User-Agent");
        ClassPathResource classPathResource = new ClassPathResource("template" + File.separator + fileName);
        try {
            InputStream inputStream = classPathResource.getInputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            if (agent.contains("MSIE")) {
                // IE浏览器
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", " ");
            } else {
                // 其它浏览器
                fileName = URLEncoder.encode(fileName, "utf-8");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            if (inputStream != null) {
                byte[] cache = new byte[2048];
                int len = 0;
                while ((len = inputStream.read(cache)) != -1) {
                    response.getOutputStream().write(cache, 0, len);
                }
            } else {
                response.setStatus(404);
            }
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("template down file error:{}" + e.getMessage());
        }

    }


    @GetMapping("download/{index}/{bizType}")
    public void dynamicTemplateDownload(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer index, @PathVariable String bizType) {
        String fileName = TemplateTypes.getFileName(index);
        try {
            ClassPathResource classPathResource = new ClassPathResource("template" + File.separator + fileName);
            InputStream inputStream = classPathResource.getInputStream();
            List<BaseDynamicFieldConfig> configList = fieldConfigService.findByBizType(bizType);
            Workbook workbook = WorkbookFactory.create(inputStream);
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                Row firstRow = sheet.getRow(sheet.getFirstRowNum());
                int startNum = firstRow.getLastCellNum();
                for (int j = startNum; j < startNum + configList.size(); j++) {
                    BaseDynamicFieldConfig config = configList.get(j - startNum);
                    CellStyle cellStyle = firstRow.getCell(startNum - 1).getCellStyle();
                    Cell newCell = firstRow.createCell(j);
                    newCell.setCellStyle(cellStyle);
                    newCell.setCellValue(config.getFieldDesc());
                }
            }
            // 重置响应对象
            response.reset();
            // 当前日期，用于导出文件名称
            // 指定下载的文件名--设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // response.setHeader("Pragma", "no-cache");
            fileName = URLEncoder.encode(fileName, "utf-8");
            String agent = request.getHeader("User-Agent");
            if (agent.contains("MSIE")) {
                // IE浏览器
                fileName = fileName.replace("+", Constant.SPLIT_SPACE);
            }
            // filename*属性，解决safari浏览器下载文件名显示utf8编码的问题
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ";filename*=utf-8''" + fileName);
            // response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            // 写出数据输出流到页面
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            logger.error("Dynamic template download error", e);
        }
    }
}
